package net.xdclass.service.impl;

import lombok.extern.slf4j.Slf4j;
import net.xdclass.component.SmsComponent;
import net.xdclass.config.SmsConfig;
import net.xdclass.constant.RedisKey;
import net.xdclass.enums.BizCodeEnum;
import net.xdclass.enums.SendCodeEnum;
import net.xdclass.service.NotifyService;
import net.xdclass.util.CommonUtil;
import net.xdclass.util.CheckUtil;
import net.xdclass.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class NotifyServiceImpl implements NotifyService {
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	private SmsComponent smsComponent;
	@Autowired
	private SmsConfig smsConfig;
	@Autowired
	private RedisTemplate redisTemplate;

	private final static long KEY_EXPIRE_TIME = 1000 * 60 * 20;

	// @Async
	public JsonData sendMessage(SendCodeEnum sendCodeEnum, String to) {
		String code = CommonUtil.getRandomCode(6);
		String message_key = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum, to);
		String get_value = (String) redisTemplate.opsForValue().get(message_key);

		if (StringUtils.isNotBlank(get_value)) {
			long ttl = Long.parseLong(get_value.split("_")[1]);
			long cur_ttl = CommonUtil.getCurrentTimestamp();
			long past_ttl = cur_ttl - ttl;
			if (past_ttl < 60 * 1000) {
				return JsonData.buildResult(BizCodeEnum.CODE_LIMITED);
			}
		}

		String message_value = code + "_" + CommonUtil.getCurrentTimestamp();
		redisTemplate.opsForValue().set(message_key, message_value, KEY_EXPIRE_TIME, TimeUnit.MILLISECONDS);
		if (CheckUtil.isEmail(to)) {
		} else if (CheckUtil.isPhone(to)) {
			smsComponent.send(to, smsConfig.getTemplateId(), code);
		}
		return JsonData.buildSuccess();
	}

	@Override
	public Boolean checkCode(SendCodeEnum sendCodeEnum, String to, String code) {
		String message_key = String.format(RedisKey.CHECK_CODE_KEY, sendCodeEnum, to);
		String get_value = (String) redisTemplate.opsForValue().get(message_key);
		if (StringUtils.isNotBlank(get_value)) {
			String send_code = get_value.split("_")[0];
			if (send_code.equals(code)) {
				redisTemplate.delete(message_key);
				return true;
			}
		}
		return false;
	}
}